package com.bs.demo.tasks;

import com.bs.demo.config.ScheduleConfig;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ScheduledFuture;


/**
 * @author bingshao
 * @date 2023/2/15
 **/
@Component
public class DynamicTask {
    private final static Logger logger = LoggerFactory.getLogger(DynamicTask.class);

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;    // 注入线程池任务调度类

    public void startCron() throws ParseException {

        getTasks().forEach(customizeTask -> {
            // 开始执行调度
            if ("1".equals(customizeTask.getType())) {
                ScheduledFuture scheduledFuture = threadPoolTaskScheduler.scheduleAtFixedRate(customizeTask, customizeTask.getStartTime(), customizeTask.getPeriod());
                // 将 scheduledFuture 保存下来用于停止任务使用
                ScheduleConfig.cache.put(customizeTask.getName(), scheduledFuture);
            }
            if ("2".equals(customizeTask.getType())) {
                ScheduledFuture scheduledFuture = threadPoolTaskScheduler.schedule(customizeTask, new CronTrigger(customizeTask.getCron()));// 将 scheduledFuture 保存下来用于停止任务使用
                ScheduleConfig.cache.put(customizeTask.getName(), scheduledFuture);
            }
            if ("3".equals(customizeTask.getType())) {
                ScheduledFuture scheduledFuture = threadPoolTaskScheduler.schedule(customizeTask, customizeTask.getStartTime());
                // 将 scheduledFuture 保存下来用于停止任务使用
                ScheduleConfig.cache.put(customizeTask.getName(), scheduledFuture);
            }


        });
    }

    public void stop(String taskId) {
        if (ScheduleConfig.cache.isEmpty()) return;
        if (ScheduleConfig.cache.get(taskId) == null) return;

        ScheduledFuture scheduledFuture = ScheduleConfig.cache.get(taskId);

        if (scheduledFuture != null) {
            scheduledFuture.cancel(true);   // 这里需要使用指定的 scheduledFuture 来停止当前的线程
            ScheduleConfig.cache.remove(taskId);        // 移除缓存
        }
    }

    public void stopAll() {
        if (ScheduleConfig.cache.isEmpty()) return;
        ScheduleConfig.cache.values().forEach(scheduledFuture -> scheduledFuture.cancel(true));
    }

    private List<CustomizeTask> getTasks() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return Arrays.asList(new CustomizeTask("任务一", "0/5 * * * * ?", "2"),
                new CustomizeTask("任务二", sdf.parse("2023-02-16 09:24:00"), "3"),
                new CustomizeTask("任务三", sdf.parse("2023-02-16 09:24:00"), 2000L, "1"));
    }

    // 自定义任务，这里用来对任务进行封装
    @Data
    private class CustomizeTask implements Runnable {
        private String name;    // 任务名字
        private String cron;    // 触发条件
        private String type;    // 间隔执行，自定义Cron表达式，只执行一次
        private Date startTime;
        private Long period;

        CustomizeTask(String name, String cron, String type) {
            this.name = name;
            this.cron = cron;
            this.type = type;
        }

        CustomizeTask(String name, Date startTime, String type) {
            this.name = name;
            this.startTime = startTime;
            this.type = type;
        }

        CustomizeTask(String name, Date startTime, Long period, String type) {
            this.name = name;
            this.startTime = startTime;
            this.period = period;
            this.type = type;
        }


        @Override
        public void run() {
            logger.info("当前任务名称：{},时间为:{}", name, new Date());
        }
    }
}

